package com.demo.web;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.web.response.PageBean;
import com.demo.web.response.Response;

/**
 * 全局配置封装参数
 */
// 包名配置变量化或者增加注解机制 注意哦，这里要加上需要扫描的包,会导致Swagger获取不到正确返回解析值
@RestControllerAdvice(basePackages = {"com.demo"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果接口返回的类型本身就是ResultVO那就没有必要进行额外的操作，返回false
        // 如果方法上加了我们的自定义注解也没有必要进行额外的操作 || returnType.hasMethodAnnotation(NotResponseBody.class)
        return !returnType.getParameterType().equals(Response.class);
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType,
        Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        // 将原本的数据包装在ResultVO里
        if (data instanceof IPage) {
            return Response.ok( new PageBean<>((IPage<?>)data));
        }
        return Response.ok(data);
    }
}
